package com.ruoyi.dataserver.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.TypeUtils;
import com.ruoyi.dataserver.model.line.LINE;
import com.ruoyi.dataserver.service.ILTXAnalyzeService;
import com.ruoyi.dataserver.service.ISearchTableService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName
 * @Package com.lab.dataserver.service.impl
 * @ClassName TopologyAnalyzeServceImpl
 * @Description 连通性逻辑层
 * @Company lab
 * @Author wangw
 * @Date 2020/7/9 0009 11:55
 * @UpdateUser
 * @UpdateDate
 * @UpdateRemark
 * @Version 1.0.0
 */
@Slf4j
@Component
public class LTXAnalyzeServceImpl implements ILTXAnalyzeService {

    @Autowired
    public JdbcTemplate jdbcTemplate;

    @Autowired
    public ISearchTableService tableService;

    @Override
    public Map analyze(Map map) {
        Map resultMap = new HashMap();
        String dm = map.get("dm").toString();           // 管线类型
        String usId1 = map.get("usId1").toString();       // USID1      管线1
        String usId2 = map.get("usId2").toString();       // USID2      管线2
        List firstLineList = new ArrayList();
        List nextLineList = new ArrayList();
        // 判断两条管线是否是同一类型,不同类型不联通
        if(!usId1.substring(0,2).equals(usId2.substring(0,2))){
            map.put("code","-1");
            map.put("msg","不是同一类型管线!");
            return null;
        }


        String tableName = tableService.searchLineTable(dm);  // 组成管线表名
        Object object1 = dispose(dm, tableName, usId1);      // 获取到第一条管线的详细信息
        Object object2 = dispose(dm, tableName, usId2);      // 获取到第一条管线的详细信息
        TypeUtils.compatibleWithJavaBean = true;    // JSON转换设置：不转换大小写
        JSONObject jsonObject1 = JSON.parseObject(JSON.toJSONString(object1));
        JSONObject jsonObject2 = JSON.parseObject(JSON.toJSONString(object2));
        String snodId2 = jsonObject2.get("SNODID").toString();
        String enodId2 = jsonObject2.get("ENODID").toString();
        String [] zb1 = new String[2];
        zb1[0] = snodId2;
        zb1[1] = enodId2;
        List dataList = new ArrayList();

        // 1. 将两条管线数据查出
        // 2. 按照上下游两种模式进行查询
        // 3. 上游： 以第一条管线的起点为参数,用终点作为查询条件进行匹配，查出的管线USID匹配第二条管线的USID，如果匹配，查询结束。不匹配，进行下游查询
        String snodId = jsonObject1.get("SNODID").toString();
        String enodId = jsonObject1.get("ENODID").toString();
        String [] zb = new String[2];
        List upIdList = new ArrayList();
        zb[0] = snodId;
        zb[1] = enodId;
        upIdList.add(zb);

        Map upMap = new HashMap();
        upMap.put("status",false);
        // 查询第一条管线上游
        upMap = queryByUpStream(jsonObject1,usId2,dm,upIdList,new ArrayList(),upMap);
        List downIdList = new ArrayList();
        List towUpIdList = new ArrayList();
        List towDownIdList = new ArrayList();
        Map downMap = new HashMap();
        Map twoUpMap = new HashMap();
        Map twoDownMap = new HashMap();

        // 上游未找到数据,寻找下游
        if(!Boolean.valueOf(upMap.get("status").toString())){
            downMap.put("status",false);
            downMap = queryByDownStream(jsonObject1,usId2,dm,downIdList,new ArrayList(),downMap);

            // 下游未找到数据,准备寻找第二条管线上游
            if(!Boolean.valueOf(downMap.get("status").toString())){
                twoUpMap.put("status",false);
                // 寻找第二根管线上游
                twoUpMap = queryByUpStream(jsonObject2,usId2,dm,towUpIdList,new ArrayList(),twoUpMap);
                // 第二条管线上游未找到数据,查询下游
                if(!Boolean.valueOf(twoUpMap.get("status").toString())){
                    twoDownMap.put("status",false);
                    // 查询下游
                    twoDownMap = queryByDownStream(jsonObject2,usId2,dm,towDownIdList,new ArrayList(),twoDownMap);

                    // 第二条管线下游未找到数据-> 全部未找到,特殊处理
                    if(!Boolean.valueOf(twoDownMap.get("status").toString())){
                        firstLineList.addAll(upIdList);
                        firstLineList.addAll(downIdList);
                        nextLineList.addAll(towUpIdList);
                        nextLineList.addAll(towDownIdList);

                        // 查看是否有交集,取第一个交集点
                        String  s = queryAlikeArray(firstLineList,nextLineList);

                        if(s != null){
                            // 从交集点出发,按上下游查询,直到找到匹配管线为止
                            // 上游查
                            map = queryUpLineByJJd(tableName,dm,s,usId1,usId2,dataList,new ArrayList(),map);

                            if(map == null || map.size() == 0){
                                // 下游查
                                map = queryDownLineByJJd(tableName,dm,s,usId1,usId2,dataList,new ArrayList(),map);
                                if(dataList == null){
                                    return null;
                                }
                            }else{
                                resultMap.put("record",map);
                                return resultMap;
                            }
                        }else{
                            return null;
                        }
                    }else{
                        resultMap.put("record",map);
                        return resultMap;
                    }
                }else{
                    resultMap.put("record",twoUpMap);
                    return resultMap;
                }
            }else{
                // 直接返回下游数据
                resultMap.put("record",downMap);
                return resultMap;
            }
        }else{
            //直接返回上游数据
            resultMap.put("record",upMap);
            return resultMap;
        }
        dataList.clear();
        downMap.clear();
        twoUpMap.clear();
        upMap.clear();
        map.clear();
        return resultMap;
    }
    
    /** 
     * @Title 查询交集方法
     * @Description
     * @return
     * @author wangw
     * @date 2020/7/28 0028 16:09
    */
    public String  queryAlikeArray(List list1,List list2){
        for (int i = 0; i < list1.size(); i++) {
            String[] n1 = (String[]) list1.get(i);
            for (int j = 0; j < list2.size(); j++) {
                String[] n2 = (String[]) list2.get(j);
                if(n1[0].equals(n2[0])){
                    return n2[0];
                }
                if(n1[1].equals(n2[1])){
                    return n2[1];
                }
            }
        }
        return null;
    }

    /** 
     * @Title 从交集点出发,按照上下游顺序寻找两条管线,找到则返回管段集合,未找到则返回null
     * @Description
     * @return
     * @author wangw
     * @date 2020/7/28 0028 15:19
    */

    /**
     * @Title
     * @Description
     * @param tableName : 表名
     * @param dm : 管线类型
     * @param snodId : 第一条管线起点
     * @param usId1 : 第一条管线USID
     * @param usId2 : 第二条管线USID
     * @param zbList : 所有点位坐标集合
     * @param dataList : 数据结果集
     * @return
     * @author wangw
     * @date 2020/7/30 0030 11:30
    */
    public Map queryUpLineByJJd(String tableName,String dm,String snodId,String usId1,String usId2,List zbList,List dataList,Map map){

        // 下游
        String sql = "select DM,QDDH,ZDDH,QDGC,ZDGC,QDMS,ZDMS,MSLX,CZ,GJ,DYZ,YL,LX,ZKS,ZYKS,DLTS,BHCZ,XX,GXFLDM,SZDL,QSDW,JSND,TCDW,TCRQ,SYZT,BZ,SNODID,ENODID,RKDATE,ISLOCK,US_ID from \"" + tableName + "\" where dm='" + dm + "' and ENODID='" + snodId + "'";
        //String sql = "select * from " + tableName + " where dm='" + dm + "' and ENODID='" + snodId + "'";
        List lineList = null;

        RowMapper<LINE> rowMapper1 = new BeanPropertyRowMapper<LINE>(LINE.class);
        lineList = jdbcTemplate.query(sql, rowMapper1);

        if(lineList.size() == 0){
            return map;
        }

        for (int i = 0; i < lineList.size(); i++) {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(lineList.get(i)));
            String[] zb = new String[2];
            zb[0] = jsonObject.get("SNODID").toString();
            zb[1] = jsonObject.get("ENODID").toString();
            zbList.add(zb);
            //dataList.add(jsonObject);
            dataList.add(lineList.get(i));
            map.put("zbList",zbList);
            map.put("dataList",dataList);
            // 判断查出的管线USID是否匹配第一/二根管线的USID，匹配则退出循环
            if (usId2.equals(jsonObject.get("US_ID")) || usId1.equals(jsonObject.get("US_ID"))) {
                break;
            } else {
                queryUpLineByJJd(tableName,dm,jsonObject.get("SNODID").toString(),usId1,usId2,zbList,dataList,map);
                continue;
            }
        }

        return map;
    }

    /**
     * @Title 从交集点出发,按照上下游顺序寻找两条管线,找到则返回管段集合,未找到则返回null
     * @Description
     * @return
     * @author wangw
     * @date 2020/7/28 0028 15:19
     */
    public Map queryDownLineByJJd(String tableName,String dm,String enodId,String usId1,String usId2,List zbList,List dataList,Map map){

        // 下游
        String sql = "select DM,QDDH,ZDDH,QDGC,ZDGC,QDMS,ZDMS,MSLX,CZ,GJ,DYZ,YL,LX,ZKS,ZYKS,DLTS,BHCZ,XX,GXFLDM,SZDL,QSDW,JSND,TCDW,TCRQ,SYZT,BZ,SNODID,ENODID,RKDATE,ISLOCK,US_ID from \"" + tableName + "\" where dm='" + dm + "' and SNODID='" + enodId + "'";

        //String sql = "select * from " + tableName + " where dm='" + dm + "' and SNODID='" + enodId + "'";
        List lineList = null;

        RowMapper<LINE> rowMapper1 = new BeanPropertyRowMapper<LINE>(LINE.class);
        lineList = jdbcTemplate.query(sql, rowMapper1);

        if(lineList.size() == 0){
            return map;
        }

        for (int i = 0; i < lineList.size(); i++) {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(lineList.get(i)));
            String[] zb = new String[2];
            zb[0] = jsonObject.get("SNODID").toString();
            zb[1] = jsonObject.get("ENODID").toString();
            zbList.add(zb);
            //dataList.add(jsonObject);
            dataList.add(lineList.get(i));

            map.put("zbList",zbList);
            map.put("dataList",dataList);

            // 判断查出的管线USID是否匹配第一/二根管线的USID，匹配则退出循环
            if (usId2.equals(jsonObject.get("US_ID")) || usId1.equals(jsonObject.get("US_ID"))) {
                break;
            } else {
                queryDownLineByJJd(tableName,dm,jsonObject.get("ENODID").toString(),usId1,usId2,zbList,dataList,map);
                continue;
            }
        }

        return map;
    }

    /**
     * @param jsb   : 第一条管线的JSON处理对象
     * @param usId2 : 第二条管线的USID
     * @param dm    : 管线类型
     * @return
     * @Title 查询上游联通管线
     * @Description
     * @author wangw
     * @date 2020/7/21 0021 11:16
     */
    public Map  queryByUpStream(JSONObject jsb, String usId2, String dm,List zbList,List dataList,Map map) {
        if (Boolean.valueOf(map.get("status").toString())) {
            return map;
        }
        String tableName = tableService.searchLineTable(dm);  // 组成管线表名
        String snodId = jsb.get("SNODID").toString();
        String sql = "select DM,QDDH,ZDDH,QDGC,ZDGC,QDMS,ZDMS,MSLX,CZ,GJ,DYZ,YL,LX,ZKS,ZYKS,DLTS,BHCZ,XX,GXFLDM,SZDL,QSDW,JSND,TCDW,TCRQ,SYZT,BZ,SNODID,ENODID,RKDATE,ISLOCK,US_ID from \"" + tableName + "\" where dm='" + dm + "' and ENODID='" + snodId + "'";
        //String sql = "select * from " + tableName + " where dm='" + dm + "' and ENODID='" + snodId + "'";
        List lineList = null;

        RowMapper<LINE> rowMapper1 = new BeanPropertyRowMapper<LINE>(LINE.class);
        lineList = jdbcTemplate.query(sql, rowMapper1);

        if(lineList != null && lineList.size()>0){
            for (int i = 0; i < lineList.size(); i++) {
                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(lineList.get(i)));

                // 拼接数组
                String [] zb = new String[2];
                zb[0] = jsonObject.get("SNODID").toString();
                zb[1] = jsonObject.get("ENODID").toString();
                zbList.add(zb);
                //dataList.add(jsonObject);
                dataList.add(lineList.get(i));
                map.put("zbList",zbList);
                map.put("dataList",dataList);
                // 判断查出的管线USID是否匹配第二根管线的USID，匹配则退出循环
                if (usId2.equals(jsonObject.get("US_ID"))) {
                    map.put("status",true);
                    break;
                } else {
                    map = queryByUpStream(jsonObject,usId2,dm,zbList,dataList,map);
                    continue;
                }
            }
        }else {
            return map;
        }
        return map;
    }

    /**
     * @param jsb   : 第一条管线的JSON处理对象
     * @param usId2 : 第二条管线的USID
     * @param dm    : 管线类型
     * @return
     * @Title 查询下游联通管线
     * @Description
     * @author wangw
     * @date 2020/7/21 0021 11:16
     */
    public Map queryByDownStream(JSONObject jsb, String usId2, String dm,List zbList,List dataList,Map map) {
        if (Boolean.valueOf(map.get("status").toString())) {
            return map;
        }
        String tableName = tableService.searchLineTable(dm);  // 组成管线表名
        String enodId = jsb.get("ENODID").toString();
        List lineList = null;
        String sql = "select DM,QDDH,ZDDH,QDGC,ZDGC,QDMS,ZDMS,MSLX,CZ,GJ,DYZ,YL,LX,ZKS,ZYKS,DLTS,BHCZ,XX,GXFLDM,SZDL,QSDW,JSND,TCDW,TCRQ,SYZT,BZ,SNODID,ENODID,RKDATE,ISLOCK,US_ID from \"" + tableName + "\" where dm='" + dm + "' and SNODID='" + enodId + "'";
        //String sql = "select * from " + tableName + " where dm='" + dm + "' and SNODID='" + enodId + "'";

        RowMapper<LINE> rowMapper1 = new BeanPropertyRowMapper<LINE>(LINE.class);
        lineList = jdbcTemplate.query(sql, rowMapper1);


        if(lineList != null && lineList.size()>0){
            for (int i = 0; i < lineList.size(); i++) {
                JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(lineList.get(i)));
                if (jsonObject != null) {
                    // 拼接数组
                    String [] zb = new String[2];
                    zb[0] = jsonObject.get("SNODID").toString();
                    zb[1] = jsonObject.get("ENODID").toString();
                    zbList.add(zb);
                    //dataList.add(jsonObject);
                    dataList.add(lineList.get(i));
                    map.put("zbList",zbList);
                    map.put("dataList",dataList);
                    // 判断查出的管线USID是否匹配第二根管线的USID，匹配则退出循环
                    if (usId2.equals(jsonObject.get("US_ID"))) {
                        map.put("status",true);
                        break;
                    } else {
                        map = queryByDownStream(jsonObject,usId2,dm,zbList,dataList,map);
                        continue;
                    }
                }
            }
        }else{
            return map;
        }
        return map;
    }

    /**
     * @return
     * @Title 根据管线类型处理数据
     * @Description
     * @author wangw
     * @date 2020/7/14 0014 11:34
     */
    public Object dispose(String dm, String tableName, String usId) {
        String sql = "select DM,QDDH,ZDDH,QDGC,ZDGC,QDMS,ZDMS,MSLX,CZ,GJ,DYZ,YL,LX,ZKS,ZYKS,DLTS,BHCZ,XX,GXFLDM,SZDL,QSDW,JSND,TCDW,TCRQ,SYZT,BZ,SNODID,ENODID,RKDATE,ISLOCK,US_ID from \"" + tableName + "\" where US_ID='" + usId + "'";
        //                    0   1   2     3    4    5    6    7   8  9  10 11 12 13   14   15   16  17  18     19    20   21  22   23   24  25  26      27     28     29     30
        Object obj = new Object();
        obj = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<LINE>(LINE.class));
        return obj;
    }

}

